package com.cy.mall.service.comm.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.cy.mall.comm.utils.JsonObjectMapper;
import com.cy.mall.comm.utils.SpringContextUtils;
import com.cy.mall.dao.mapper.bank.BankMapper;
import com.cy.mall.dao.mongodb.BankCardInfoDao;
import com.cy.mall.model.Result;
import com.cy.mall.model.doc.BankCardInfo;
import com.cy.mall.model.domain.bank.Bank;
import com.cy.mall.model.dto.bank.BankCardVerifyParamDTO;
import com.cy.mall.service.BaseService;
import com.cy.mall.service.comm.BankCardService;

import lombok.extern.slf4j.Slf4j;

/**
 * 阿里云 银行卡 服务 AliBankCardServiceImpl
 *
 * @author tanyilin
 *
 * @create 2019年2月27日 下午5:16:07
 */
@Slf4j
@Service
public class AliBankCardServiceImpl extends BaseService implements BankCardService {

	@Value("${bankcard.location-query-url}")
    private String queryUrl;
    @Value("${bankcard.verify-url}")
    private String verifyUrl;
    @Value("${bankcard.app-code}")
    private String appCode;
    
    @Autowired
    private RestTemplate restTemplate;
    private HttpEntity httpEntity;
    @Autowired
    private BankMapper bankMapper;
    @Autowired
    private BankCardInfoDao bankCardInfoDao;
    
    @PostConstruct
    private void initHttpEntity() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "APPCODE ".concat(appCode));
        httpEntity = new HttpEntity(null, headers);
    }

	@Override
	public Result verifyBankCard(BankCardVerifyParamDTO bankCardVerifyParamDTO) {

		//设置参数
		Map<String, String> params = new HashMap<>();
        params.put("mobile", bankCardVerifyParamDTO.getMobile());
        params.put("bankcard", bankCardVerifyParamDTO.getBankcard());
        params.put("cardNo", bankCardVerifyParamDTO.getCardNo());
        params.put("realName", bankCardVerifyParamDTO.getRealName());
        
        log.info("银行卡[{}]四要素验证。参数params: {}", bankCardVerifyParamDTO.getBankcard(), params);
        
        ResponseEntity<String> responseEntity = restTemplate.exchange(verifyUrl, HttpMethod.GET, httpEntity, String.class, params);
        
        if(!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
        	return Result.fail("验证银行卡请求异常");
        }
        
        log.info("银行卡四要素验证回调报文：{}", responseEntity.getBody());
        
        Map<String, Object> body = JsonObjectMapper.read(responseEntity.getBody(), Map.class);
        if (!Integer.valueOf(0).equals(body.get("error_code"))) {
            return Result.fail("验证银行卡失败，原因： " + body.get("reason"));
        }
        
        Map<String, Object> result = (Map) body.get("result");
		
		return Result.success("验证银行卡成功", result);
	}

	@Override
	public Result queryBankCard(String bankCard) {
		Date time = new Date();
		
		//查询历史数据
        BankCardInfo historyInfo = bankCardInfoDao.findByBankCard(bankCard);
        if (historyInfo != null) {
            log.info("查询银行卡归属地[{}],获取历史数据。", bankCard);
            return Result.success("银行卡归属地查询成功", historyInfo.getData());
        }
		
		//设置参数
        Map<String, Object> params = new HashMap<>();
        params.put("apiversion", "2.0.5");
        params.put("bankcard", bankCard);
        log.info("银行卡[{}]查询归属地。参数param:{}", bankCard, params);
        
        //发起请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(queryUrl, HttpMethod.GET, httpEntity, String.class, params);
        
        if (!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
            return Result.fail("银行卡归属地查询 请求异常");
        }
        
        log.info("银行卡归属地查询回调报文：{}", responseEntity.getBody());
        
        Map<String, Object> body = JsonObjectMapper.read(responseEntity.getBody(), Map.class);
        if (!Integer.valueOf(0).equals(body.get("error_code"))) {
            return Result.fail("银行卡归属地查询失败，原因：" + body.get("reason"));
        }
        
        Map<String, Object> result = (Map) body.get("result");
        
        //记录数据到MongoDB
        BankCardInfo bankCardInfo = new BankCardInfo();
        bankCardInfo.setBankCard(bankCard);
        bankCardInfo.setData(result);
        bankCardInfo.setCreateTime(time);
        bankCardInfoDao.insert(bankCardInfo);
        
        log.info("保存银行卡信息");
        try {
            String bankNo = result.get("banknum").toString();
            String bankName = result.get("bankname").toString();
            Object iconImg = result.get("bankimage");
            Object code = result.get("abbreviation");
            
            Bank bank = new Bank();
            bank.setBankNo(bankNo);
            bank.setBankName(bankName);
            bank.setIconImg(iconImg == null ? null : String.valueOf(iconImg));
            bank.setCode(code == null ? null : String.valueOf(code));
            bank.setCreateTime(time);
            bank.setUpdateTime(time);
            
            SpringContextUtils.getBean(BankCardService.class).insertBank(bank);
            
        } catch (Exception e) {
            log.error("保存银行信息异常：", e);
        }
        
        return Result.success("银行卡归属地查询成功", result);
	}

	@Override
    @Transactional
    public void insertBank(Bank bank) {
        Bank dbBank = new Bank();
        dbBank.setBankNo(bank.getBankNo());
        int count = bankMapper.selectCount(dbBank);
        if (count <= 0) {
            bankMapper.insertSelective(bank);
        }
    }
	
    
    
}
